import 'dart:convert';
import 'dart:math';
import 'package:base_flutter/base_flutter.dart';
import 'package:ble_measure_plugin/ble_measure_plugin.dart';
import 'package:ble_measure_plugin/connect_devices_utils.dart';
import 'package:dio/dio.dart';
import 'package:flustars_flutter3/flustars_flutter3.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:ls_work/a_yyt/models/medical_service_entity.dart';
import 'package:ls_work/a_yyt/page/medical_history_page.dart';
import 'package:ls_work/mvp/svp_progress.dart';
import 'package:ls_work/net/HttpUtil.dart';
import 'package:ls_work/net/net.dart';
import 'package:ls_work/net/post_request.dart';
import 'package:ls_work/res/colors.dart';
import 'package:ls_work/a_yyt/models/medical_elder_entity.dart';
import 'package:ls_work/res/gaps.dart';
import 'package:ls_work/res/styles.dart';
import 'package:ls_work/util/app_navigator.dart';
import 'package:ls_work/util/event_bus.dart';
import 'package:ls_work/util/toast.dart';
import 'package:flutter_blue_plus/flutter_blue_plus.dart';
import 'package:ls_work/widgets/base_dialog.dart';
import 'package:oktoast/oktoast.dart';
import 'package:pc300_health_sdk/health_data_plugin.dart';

import '../../util/flat_button.dart';

class MedicalCheckPage extends StatefulWidget {
  MedicalElderInfo? info;
  bool isOnConnectDevice = false;
  Function(bool isConnectDevice)? callBack;
  bool needPc304;

  MedicalCheckPage(
      {Key? key,
      this.info,
      this.isOnConnectDevice = false,
      this.callBack,
      this.needPc304 = true});

  @override
  _MedicalCheckPageState createState() => _MedicalCheckPageState();
}

class _MedicalCheckPageState extends State<MedicalCheckPage> {
  double _opacity = 0.0;

  bool _highPreSelected = true;
  bool _lowPreSelected = true;
  bool _oxygenSelected = true;
  bool _heartSelected = true;
  bool _temperatureSelected = true;
  bool _bloodSugarSelected = true;

  String _highPreValue = '-';
  String _lowPreValue = '-';
  String _oxygenValue = '-';
  String _heartValue = '-';
  String _temperatureValue = '-';
  String _bloodSugarValue = '-';

  int? _bizType301;
  int? _bizType302;
  int? _bizType303;
  int? _bizType304;
  int? _bizType60;

  MedicaServiceModel? _serviceModel;
  List<MedicaServiceInfo> dataList = [];
  BluetoothDevice? device;
  String _deviceAddress = '';

  ///蓝牙是否开启
  bool isOnBluetooth = true;
  bool _isOnConnectDevice = false;

  // FlutterBlue _flutterBlue;

  // BluetoothState _bluState;
  // String _platformVersion = 'Unknown';

  bool _isHeartWave = true;
  double _topMargin = double.infinity;

  OnDeviceStateListener? _deviceListener;

  @override
  void initState() {
    super.initState();
    // _flutterBlue = FlutterBlue.instance;
    ConnectDeviceUtils.initMeasureDevice();
    BleMeasurePlugin.instance.addDeviceConnectListener(
        onStartConnectListener: (s) async {
      Toast.showStateWithMsg("正在连接设备...");
    }, onStartOpenListener: (s) async {
      Toast.cancelToast();
      Toast.showStateWithMsg("正在开启服务...");
    }, onOpenSuccessListener: (s) async {
      Toast.cancelToast();
    });
    _isOnConnectDevice = widget.isOnConnectDevice;
    _deviceListener = (event) {
      if (event.hasLink) {
        Toast.cancelToast();
      }
      setState(() {
        _isOnConnectDevice = HealthDeviceLinkUtils.isOnline || event.hasLink;
      });
    };

    setState(() {
      _isOnConnectDevice = HealthDeviceLinkUtils.isOnline ||
          BleMeasurePlugin.instance.linkDevices.isNotEmpty;
    });

    ConnectDeviceUtils.addOnDeviceStateListener(_deviceListener!);
    HealthDeviceLinkUtils.initListener(onFinish: () {
      Toast.cancelToast();
      if (HealthDeviceLinkUtils.deviceList.isNotEmpty) {
        var device = HealthDeviceLinkUtils.deviceList[0];
        Toast.showStateWithMsg("正在连接设备...");
        HealthDeviceLinkUtils.linkDevice(device);
      } else {
        Toast.show("未搜索到健康设备");
      }
    }, onLinkSuccess: () {
      Toast.cancelToast();
      setState(() {
        _isOnConnectDevice = true;
        Toast.showSuccessWithMsg('蓝牙链接成功');
      });
      Log.d("", "success=======>111");
    }, onLinkError: (error) {
      setState(() {
        Log.d("", '链接失败状态 - 🥕$error');
        HealthDeviceLinkUtils.isOnline = false;
        _isOnConnectDevice = HealthDeviceLinkUtils.isOnline ||
            ConnectDeviceUtils.stateModel.hasLink;
      });
      // if(HealthDeviceLinkUtils.deviceList.isNotEmpty){
      //   var device = HealthDeviceLinkUtils.deviceList[0];
      //   HealthDeviceLinkUtils.linkDevice(device);
      // }
    });

    if (!_isOnConnectDevice && widget.needPc304) {
      Future.delayed(Duration(seconds: 1), () {
        _searchToast();
      });
    }
    WidgetsBinding.instance.addPostFrameCallback((_) {
      /// 接口请求
      // initPlatformState();
      _fectData();
    });

    ///体温仪器
    BleMeasurePlugin.instance.addTemMeasureListener(
      temHandeler: (data) async {
        Log.d("", "receiveTemData===>${data}");
        var value = data.temValue;
        var measureState = data.measureType;
        setState(() {
          if (measureState == "30" || measureState == "0") {
            _temperatureValue = value ?? "";
          }
        });
      },
      temErrorHandler: (error) async {
        // Log.d("","temerror===>$error");
        showToast(error);
      },
    );

    BleMeasurePlugin.instance.addPressureMeasureListener(
        pressureMeasuringHandler: (measureData) async {
      setState(() {
        // _lowPreValue = measureData;
        // _highPreValue = "-";
        // _heartValue = "-";
      });
    }, pressureResultHandler: (data) async {
      setState(() {
        // measureResult = "收缩压：${data.highPressure}"
        //     "舒张压：${data.lowPressure}  脉率：${data.pulse},\n是否误动：${data.bodyMove == "0" ? "否" : "是"},";
        _lowPreValue = data.lowPressure ?? "";
        _highPreValue = data.highPressure ?? "";
        _heartValue = data.pulse ?? "";
      });
    });

    BleMeasurePlugin.instance.addBloodSugarMeasureListener(
        bloodSugarHandler: (data) async {
      setState(() {
        _bloodSugarValue = data.value ?? "";
      });
    });

    HealthDataSdk.getInstance().addHealthDataHandler(onGetTmp: (data) async {
      ///体温数据
      var result = data["nResultStatus"].toString();
      bool bProbeOff = data["bProbeOff"];

      if (result == "0" && bProbeOff) {
        double value = data["nTmp"] / 100 + 30;
        Log.d("", value);
        setState(() {
          String valueStr = value.toString();
          _temperatureValue = valueStr.substring(0, valueStr.indexOf(".") + 2);
        });
      }
    }, onGetNIBPRealTime: (data) async {
      ///血压测量实时数据
      // String msg = "血压测量数据：" + data["nBldPrs"].toString();
      if (int.parse(data["nBldPrs"].toString()) > 300) {
        return;
      }
      setState(() {
        _highPreValue = data["nBldPrs"].toString();
      });
    }, onGetNIBPResult: (data) async {
      ///血压测量结果
      // String msg = "血压测量结果：\n收缩压：" +
      //     data["nSYS"].toString() +
      //     "\n舒张压：" +
      //     data["nDIA"].toString();
      if (data["errorMsg"].toString().trim().isEmpty) {
        setState(() {
          _highPreValue = data["nSYS"].toString();
          _lowPreValue = data["nDIA"].toString();
          _heartValue = data['nPulse'].toString();
        });
      } else {
        _highPreValue = "";
        _lowPreValue = "";
        _heartValue = "";
      }
    }, onGetSpO2Wave: (data) async {
      // OxgenWaveDataModel;
      _opacity = 1.0;

      ///获取到血氧波形数据
      if ((data.waveData ?? []).isNotEmpty) {
        setState(() {
          _isHeartWave = data.waveData!.first.data! % 2 == 0;
          _topMargin = Random().nextDouble();
        });
      }
    }, onGetSpO2Param: (data) async {
      // Log.d("", '🍎🍎🍎🍎- ${data}');

      ///获取血氧参数
      setState(() {
        //nStatus
        if (data['nStatus'] == 4) {
          return;
        }
        if (data["nStatus"] == 0) {
          if (data["nSpO2"] != 0) {
            _oxygenValue = data['nSpO2'].toString();
            _heartValue = data['nPR'].toString();
          }
        } else {
          showToast('探头脱落', context: context);
          _topMargin = 0.0;
          _opacity = 0.0;
        }
      });
    }, onGetECGAction: (data) async {
      ///心电测量状态改变
      // setState(() {
      //   _tmp = data.toString();
      // });
    }, onGetECGRealTime: (data) async {
      ///获取心电实时数据
      // EcgDataModel ecgData = EcgDataModel.fromJson(data);
      // setState(() {
      //   _tmp = ecgData.ecgdata.data[0].data.toString();
      // });
    }, onGetECGResult: (data) async {
      ///获取心电结果
      ///data:{resultMsg: 疑似心跳间期不规则 请咨询医生, nHR: 86, nResult: 7}
      setState(() {
        _heartValue = data['nHR'].toString();
      });
    }, onGetPowerOff: (data) async {
      ///下位机关机
      Toast.show("设备关机");
      HealthDeviceLinkUtils.isOnline = false;
      setState(() {
        _isOnConnectDevice = false;
      });

      // eventBus.emit("deviceOff");
      //   Toast.show("设备关机");
      // Navigator.pop(context);
    }, onConnectLose: (data) async {
      ///设备丢失
      HealthDeviceLinkUtils.release();
      showToast("连接已断开", context: context);
      // Navigator.pop(context);
      Navigator.pop(context);
      // eventBus.emit("deviceOff");
      // setState(() {
      //   _isOnConnectDevice = _isOnConnectDevice = false;
      // _isOnConnectDevice = HealthDeviceLinkUtils.isOnline ||
      //     ConnectDeviceUtils.stateModel.hasLink;
      // });

      // setState(() {
      //   _tmp = data.toString();
      // });
    });
    // _makeValue();
  }

  _showBlueToothDialog() {
    showDialog(
      context: context,
      barrierDismissible: false,
      builder: (_) => BaseDialog(
        title: "提示",
        child: const Padding(
          padding: const EdgeInsets.symmetric(horizontal: 16.0, vertical: 8.0),
          child: const Text("是否打开蓝牙？", style: TextStyles.textDark16),
        ),
        onPressed: () async {
          await HealthDataSdk.openDevice();
          Navigator.of(context).pop();
          _searchToast();
        },
      ),
    );
  }

  @override
  void dispose() {
    Toast.cancelToast();
    if (_deviceListener != null) {
      ConnectDeviceUtils.removeListener(_deviceListener!);
    }
    BleMeasurePlugin.instance.addDeviceConnectListener();
    BleMeasurePlugin.instance.addTemMeasureListener();
    super.dispose();
  }

  void _resetValue() {
    setState(() {
      _highPreValue = '-';
      _lowPreValue = '-';
      _oxygenValue = '-';
      _heartValue = '-';
      _temperatureValue = '-';
      _bloodSugarValue = '-';
    });
  }

  // Platform messages are asynchronous, so we initialize in an async method.
  Future<void> initPlatformState() async {
    try {
      isOnBluetooth = await HealthDataSdk.isOpen();
      Log.d("", 'isOpen - $isOnBluetooth');

      if (isOnBluetooth && !_isOnConnectDevice) {
        _searchToast();
      }
    } on PlatformException {}

    if (!mounted) return;
  }

  _searchToast() {
    Toast.showStateWithMsg('正在搜索设备...', seconds: 10);
    _searchBlueToothDevice();
  }

  _searchBlueToothDevice() {
    HealthDataSdk.startDiscovery(maxTime: 10);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('${widget.info?.name??""} ${widget.info?.roomNo??""}'),
        elevation: 0.5,
        actions: [
          FlatsButton(
            onPressed: () {
              AppNavigator.push(
                context,
                MedicalHistoryPage(
                  info: widget.info,
                ),
              );
            },
            child: Text(
              '历史记录',
              style: TextStyle(fontSize: 16, color: Colours.app_main),
            ),
          )
        ],
      ),
      body: Container(
        color: Colours.bg_gray,
        width: ScreenUtil.getScreenW(context),
        height: ScreenUtil.getScreenH(context),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.start,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            if (widget.needPc304)
              Row(
                children: [
                  Expanded(child: SizedBox()),
                  ElevatedButton(
                    onPressed: () {
                      if (_isOnConnectDevice) {
                        Toast.show("设备已连接");
                      } else {
                        _searchToast();
                      }
                    },
                    child: Row(
                      children: [
                        Icon(Icons.bluetooth),
                        Text(_isOnConnectDevice ? "已连接" : "未连接"),
                      ],
                    ),
                    style: ButtonStyle(
                        backgroundColor: WidgetStateProperty.all(
                      _isOnConnectDevice ? Colours.app_main : Colours.text_gray,
                    )),
                  ),
                  Gaps.hGap15,
                ],
              ),
            Card(
              margin: EdgeInsets.fromLTRB(15, 0, 15, 0),
              elevation: 15.0, //设置阴影
              shape: const RoundedRectangleBorder(
                  borderRadius: BorderRadius.all(Radius.circular(8.0))), //设置圆角
              child: Container(
                padding: EdgeInsets.fromLTRB(0, 0, 0, 30),
                child: new Column(
                  children: [
                    Row(
                      mainAxisAlignment: MainAxisAlignment.start,
                      children: [
                        _getMedicalItem(
                            titile: '收缩压',
                            value: _highPreValue,
                            unit: 'mmhg',
                            type: 0,
                            isSelected: _highPreSelected),
                        _getMedicalItem(
                            titile: '舒张压',
                            value: _lowPreValue,
                            unit: 'mmhg',
                            type: 1,
                            isSelected: _lowPreSelected),
                        _getMedicalItem(
                            titile: '  血氧  ',
                            value: _oxygenValue,
                            unit: '%',
                            type: 2,
                            isSelected: _oxygenSelected),
                        // _getMedicalItem(titile: '心率',value: '--',isSelected: _heartSelected),
                        // _getMedicalItem(titile: '体温',value: '--',isSelected: _temperatureSelected),
                      ],
                    ),
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceAround,
                      children: [
                        // _getMedicalItem(titile: '收缩压',value: '--',isSelected: _highPreSelected),
                        // _getMedicalItem(titile: '舒张压',value: '--',isSelected: _lowPreSelected),
                        // _getMedicalItem(titile: '血氧',value: '--',isSelected: _oxygenSelected),
                        _getMedicalItem(
                            titile: '  心率  ',
                            value: _heartValue,
                            unit: '次/分',
                            type: 3,
                            isSelected: _heartSelected),
                        _getMedicalItem(
                            titile: '  体温  ',
                            value: _temperatureValue,
                            unit: '℃',
                            type: 4,
                            isSelected: _temperatureSelected),
                        _getMedicalItem(
                            titile: '  血糖  ',
                            value: _bloodSugarValue,
                            unit: 'mmol/L',
                            type: 5,
                            isSelected: _bloodSugarSelected),
                      ],
                    ),
                  ],
                ),
              ),
            ),
            Gaps.vGap16,
            Expanded(
              child: Container(
                padding: EdgeInsets.fromLTRB(15, 15, 15, 0),
                color: Colors.white,
                child: Center(
                  child: Row(
                    children: [
                      Expanded(
                        child: Container(),
                      ),
                      Column(
                        mainAxisAlignment: MainAxisAlignment.start,
                        children: [
                          Opacity(
                            opacity: _isHeartWave ? 1 : 0,
                            child: Icon(
                              Icons.favorite,
                              color: Colours.app_main,
                              size: 30,
                            ),
                          ),
                          Expanded(
                            child: Stack(
                              children: [
                                Container(
                                  width: 20,
                                  decoration: BoxDecoration(
                                    color: Colours.bg_color,
                                    border: Border.all(
                                        color: Colours.app_main, width: 0.5),
                                  ),
                                ),
                                Positioned(
                                  bottom: 0,
                                  left: 0,
                                  right: 0,
                                  top: _topMargin * 100,
                                  child: Container(
                                    width: 20,
                                    decoration: BoxDecoration(
                                      color: Colours.app_main,
                                    ),
                                  ),
                                ),
                              ],
                            ),
                          ),
                        ],
                      ),
                    ],
                  ),
                ),
              ),
            ),
            Container(
              color: Colors.white,
              padding: EdgeInsets.all(20),
              // height: 100,
              child: Flex(
                direction: Axis.horizontal,
                children: <Widget>[
                  Expanded(
                    flex: 1,
                    child: SizedBox(
                      height: 50,
                      child: FlatsButton(
                        padding: EdgeInsets.zero,
                        color: Colours.text_gray,
                        highlightColor: Colors.grey[700]!,
                        child: Text(
                          "重新测量",
                          style: TextStyle(fontSize: 15),
                        ),
                        shape: RoundedRectangleBorder(
                            borderRadius: BorderRadius.circular(25.0)),
                        onPressed: _resetValue,
                      ),
                    ),
                  ),
                  Gaps.hGap16,
                  Expanded(
                    flex: 1,
                    child: SizedBox(
                      height: 50,
                      child: FlatsButton(
                        padding: EdgeInsets.zero,
                        color: Colors.orange,
                        highlightColor: Colors.orange[700]!,
                        child: Text(
                          "提交测量结果",
                          style: TextStyle(fontSize: 15),
                        ),
                        shape: RoundedRectangleBorder(
                            borderRadius: BorderRadius.circular(25.0)),
                        onPressed: () {
                          if (!_hasHealthData()) {
                            showToast("没有可提交的健康数据");
                            return;
                          }
                          if (dataList.length <= 0) {
                            _sendNullServiceData();
                          } else {
                            _bottomServiceSheetAlert();
                          }
                        },
                      ),
                    ),
                  ),
                  Gaps.hGap16,
                  Expanded(
                    flex: 1,
                    child: SizedBox(
                      height: 50,
                      child: FlatsButton(
                        padding: EdgeInsets.zero,
                        color: Colors.white,
                        child: Text(
                          "发送至家属",
                          style: TextStyle(
                              fontSize: 15, color: Colors.orange[700]),
                        ),
                        shape: RoundedRectangleBorder(
                            borderRadius: BorderRadius.circular(25.0),
                            side: BorderSide(
                                color: Colors.orange[700]!, width: 1)),
                        onPressed: () {
                          SVProgressHUD page = SVProgressHUD(context);
                          page.showProgress(hint: "正在发送...");
                          Future.delayed(Duration(seconds: 1), () {
                            page.closeProgress();
                            showToast("已发送成功",
                                position: ToastPosition.center,
                                textStyle: TextStyle(
                                  fontSize: 16,
                                ));
                          });
                        },
                      ),
                    ),
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _getMedicalItem(
      {String? titile, String? value, String? unit, int? type, bool isSelected = true}) {
    return Container(
      padding: EdgeInsets.only(top: 30),
      width: (ScreenUtil.getScreenW(context) - 30) / 3,
      child: titile != null
          ? Column(
              children: [
                ChoiceChip(
                  label: Text(titile),
                  selected: isSelected,
                  selectedColor: Colours.app_main,
                  backgroundColor: Colours.bg_color,
                  onSelected: (value) {
                    Log.d("", value);
                    setState(() {
                      switch (type) {
                        case 0:
                          _highPreSelected = value;
                          break;
                        case 1:
                          _lowPreSelected = value;
                          break;
                        case 2:
                          _oxygenSelected = value;
                          break;
                        case 3:
                          _heartSelected = value;
                          break;
                        case 4:
                          _temperatureSelected = value;
                          break;
                        case 5:
                          _bloodSugarSelected = value;
                          break;
                        default:
                      }
                    });
                    // isSelected = value;
                    ////体温 301 血压 302 心率303 血氧 304 血糖 60
                    if (_serviceModel != null) {
                      dataList.clear();
                      _bizType301 = null;
                      for (var item in (_serviceModel!.rows??<MedicaServiceInfo>[])) {
                        if (item.bizType == 301 && _temperatureSelected) {
                          if (_bizType301 == null) {
                            _bizType301 = item.id;
                            item.isSelected = true;
                          } else {
                            item.isSelected = false;
                          }
                          dataList.add(item);
                        }
                      }
                      _bizType302 = null;
                      for (var item in (_serviceModel!.rows??<MedicaServiceInfo>[])) {
                        if (item.bizType == 302 &&
                            (_lowPreSelected || _highPreSelected)) {
                          if (_bizType302 == null) {
                            _bizType302 = item.id;
                            item.isSelected = true;
                          } else {
                            item.isSelected = false;
                          }
                          dataList.add(item);
                        }
                      }
                      _bizType303 = null;
                      for (var item in (_serviceModel!.rows??<MedicaServiceInfo>[])) {
                        if (item.bizType == 303 && _heartSelected) {
                          if (_bizType303 == null) {
                            _bizType303 = item.id;
                            item.isSelected = true;
                          } else {
                            item.isSelected = false;
                          }
                          dataList.add(item);
                        }
                      }
                      _bizType304 = null;
                      for (var item in (_serviceModel!.rows??<MedicaServiceInfo>[])) {
                        if (item.bizType == 304 && _oxygenSelected) {
                          if (_bizType304 == null) {
                            _bizType304 = item.id;
                            item.isSelected = true;
                          } else {
                            item.isSelected = false;
                          }
                          dataList.add(item);
                        }
                      }
                      _bizType60 = null;
                      for (var item in (_serviceModel!.rows??<MedicaServiceInfo>[])) {
                        if (item.bizType == 60 && _bloodSugarSelected) {
                          if (_bizType60 == null) {
                            _bizType60 = item.id;
                            item.isSelected = true;
                          } else {
                            item.isSelected = false;
                          }
                          dataList.add(item);
                        }
                      }
                    }
                    // });
                  },
                ),
                Text.rich(TextSpan(children: [
                  TextSpan(
                    text: value,
                    style: TextStyles.textDark20,
                  ),
                  TextSpan(
                    text: "  $unit",
                    style: TextStyles.textGray14,
                  ),
                ])),
              ],
            )
          : Container(),
    );
  }

  _sendNullServiceData() {
    ///无服务计划
    ///

    List nullServiceList = [];
    //体温 301 血压 302 心率303 血氧 304
    if ((_highPreSelected || _lowPreSelected) &&
        (_highPreValue != '-' && _lowPreValue != '-')) {
      Map map = {
        'id': null,
        'customerElderId': widget.info?.id,
        'bizType': 302,
        'executeStatus': 0,
        'remark': '',
        'expenseItemId': 160,
        'finishTime':
            DateUtil.formatDate(DateTime.now(), format: DateFormats.full),
      };

      MedicaServiceInfo? info;
      for (var item in dataList) {
        if (item.bizType == 302 && item.isSelected==true) {
          map['id'] = item.id;
          map['expenseItemId'] = item.expenseItemId;
          info = item;
          break;
        }
      }
      var temp = [];
      temp.add({
        'value': _highPreValue,
        'rangeTo': (map['id'] != null && (info?.result??[]).length > 0)
            ? info?.result!.first.rangeTo
            : '',
        'rangeFrom': (map['id'] != null && (info?.result??[]).length > 0)
            ? info?.result!.first.rangeFrom
            : '',
        'subItem': '收缩压',
      });
      temp.add({
        'value': _lowPreValue,
        'rangeTo': (map['id'] != null && (info?.result??[]).length > 0)
            ? info!.result!.last.rangeTo
            : '',
        'rangeFrom': (map['id'] != null && (info?.result??[]).length > 0)
            ? info!.result!.last.rangeTo
            : '',
        'subItem': '舒张压',
      });
      map['result'] = jsonEncode(temp);
      nullServiceList.add(map);
    }
    if (_oxygenSelected && _oxygenValue != '-') {
      Map map = {
        'id': null,
        'customerElderId': widget.info?.id,
        'bizType': 304,
        'executeStatus': 0,
        'remark': '',
        'expenseItemId': 162,
        'finishTime':
            DateUtil.formatDate(DateTime.now(), format: DateFormats.full),
      };
      MedicaServiceInfo? info;
      for (var item in dataList) {
        if (item.bizType == 304 && item.isSelected==true) {
          map['id'] = item.id;
          map['expenseItemId'] = item.expenseItemId;
          info = item;
          break;
        }
      }
      // if(info!=null){
        var temp = [];
        temp.add({
          'value': _oxygenValue,
          'rangeTo': map['id'] != null ? info?.result?.last.rangeTo : '',
          'rangeFrom': map['id'] != null ? info?.result?.last.rangeTo : '',
          'subItem': '血氧',
        });
        map['result'] = jsonEncode(temp);
      // }
      nullServiceList.add(map);
    }
    if (_heartSelected && _heartValue != '-') {
      Map map = {
        'id': null,
        'customerElderId': widget.info?.id,
        'bizType': 303,
        'executeStatus': 0,
        'remark': '',
        'expenseItemId': 161,
        'finishTime':
            DateUtil.formatDate(DateTime.now(), format: DateFormats.full),
      };
      MedicaServiceInfo? info;
      for (var item in dataList) {
        if (item.bizType == 303 && item.isSelected== true) {
          map['id'] = item.id;
          map['expenseItemId'] = item.expenseItemId;
          info = item;
          break;
        }
      }
      // if(info!=null){
        var temp = [];
        temp.add({
          'value': _heartValue,
          'rangeTo': map['id'] != null ? info?.result?.last.rangeTo : '',
          'rangeFrom': map['id'] != null ? info?.result?.last.rangeTo : '',
          'subItem': '心率',
        });
        map['result'] = jsonEncode(temp);
      // }
      nullServiceList.add(map);
    }
    if (_temperatureSelected && _temperatureValue != '-') {
      Map map = {
        'id': null,
        'customerElderId': widget.info?.id,
        'bizType': 301,
        'executeStatus': 0,
        'remark': '',
        'expenseItemId': 159,
        'finishTime':
            DateUtil.formatDate(DateTime.now(), format: DateFormats.full),
      };
      //体温 301 血压 302 心率303 血氧 304
      MedicaServiceInfo? info;
      for (var item in dataList) {
        if (item.bizType == 301 && item.isSelected==true) {
          map['id'] = item.id;
          map['expenseItemId'] = item.expenseItemId;
          info = item;
          break;
        }
      }
      // if(info!=null){
        var temp = [];
        temp.add({
          'value': _temperatureValue,
          'rangeTo': map['id'] != null ? info?.result?.last.rangeTo : '',
          'rangeFrom': map['id'] != null ? info?.result?.last.rangeTo : '',
          'subItem': '体温',
        });
        map['result'] = jsonEncode(temp);
      // }
      nullServiceList.add(map);
    }

    ///血糖测量
    if (_bloodSugarSelected && _bloodSugarValue != '-') {
      Map map = {
        'id': null,
        'customerElderId': widget.info?.id,
        'bizType': 60,
        'executeStatus': 0,
        'remark': '',
        'expenseItemId': 72,
        'finishTime':
            DateUtil.formatDate(DateTime.now(), format: DateFormats.full),
      };
      //体温 301 血压 302 心率303 血氧 304 血糖60
      MedicaServiceInfo? info;
      for (var item in dataList) {
        if (item.bizType == 60 && item.isSelected==true) {
          map['id'] = item.id;
          map['expenseItemId'] = item.expenseItemId;
          info = item;
          break;
        }
      }
      // if(info!=null){
        var temp = [];
        temp.add({
          'value': _bloodSugarValue,
          'rangeTo': map['id'] != null ? info?.result?.last.rangeTo : '',
          'rangeFrom': map['id'] != null ? info?.result?.last.rangeTo : '',
          'subItem': '血糖值',
          'property': '其他'
        });
        map['result'] = jsonEncode(temp);
      // }
      nullServiceList.add(map);
    }

    Log.d("", nullServiceList);
    SVProgressHUD page = SVProgressHUD(context);
    page.showProgress();
    HttpUtil.instance
        .getDio()
        .post(
          '${HttpApi.submitMedicalExaminationData}?jsonStr=${jsonEncode(nullServiceList)}',
        )
        .then((r) {
      //data: {"jsonStr": nullServiceList}
      ///
      page.closeProgress();
      if (r.statusCode == 200) {
        Map<String, dynamic> map = json.decode(r.toString());
        if (map["code"].toString() == "0") {
          if (map['data'] != null && map['data'].toString().isNotEmpty) {
            _fectData();
            Toast.show(map["msg"]);
          } else {
            Toast.show(map["msg"]);
            Navigator.of(context).pop();
          }
        } else {
          Toast.show(map["msg"]);
        }
      } else {
        Toast.show(r.statusCode.toString());
      }
    }).catchError((e) {
      page.closeProgress();
      Log.d("", e.toString());
      Toast.show(getErrorMessage(e));
    });
  }

  _fectData() {
    var map = {
      'page': 1,
      'rows': 100,
      'customerElderId': widget.info?.id,
      'status': 0,
      'isToday': true
    };
    // SVProgressHUD page = SVProgressHUD(context);
    // page.showProgress();
    HttpUtil.instance
        .getDio()
        .post('${HttpApi.myPlanRecordBeanList}', data: map,options: PostRequest.urlencodedHeader)
        .then((r) {
      // ///
      // page.closeProgress();
      if (r.statusCode == 200) {
        Map<String, dynamic> map = json.decode(r.toString());
        if (map["code"].toString() == "0") {
          if (map['data'] != null) {
            MedicaServiceModel model = MedicaServiceModel.fromJson(map['data']);
            _serviceModel = model;
            if ((model.rows??[]).length > 0) {
              //体温 301 血压 302 心率303 血氧 304
              for (var item in (model.rows??<MedicaServiceInfo>[])) {
                if (item.bizType == 301) {
                  if (_bizType301 == null) {
                    _bizType301 = item.id;
                    item.isSelected = true;
                  } else {
                    item.isSelected = false;
                  }
                  dataList.add(item);
                }
              }
              for (var item in (model.rows??<MedicaServiceInfo>[])) {
                if (item.bizType == 302) {
                  if (_bizType302 == null) {
                    _bizType302 = item.id;
                    item.isSelected = true;
                  } else {
                    item.isSelected = false;
                  }
                  dataList.add(item);
                }
              }
              for (var item in (model.rows??<MedicaServiceInfo>[])) {
                if (item.bizType == 303) {
                  if (_bizType303 == null) {
                    _bizType303 = item.id;
                    item.isSelected = true;
                  } else {
                    item.isSelected = false;
                  }
                  dataList.add(item);
                }
              }
              for (var item in (model.rows??<MedicaServiceInfo>[])) {
                if (item.bizType == 304) {
                  if (_bizType304 == null) {
                    _bizType304 = item.id;
                    item.isSelected = true;
                  } else {
                    item.isSelected = false;
                  }
                  dataList.add(item);
                }
              }

              for (var item in (model.rows??<MedicaServiceInfo>[])) {
                if (item.bizType == 60) {
                  if (_bizType60 == null) {
                    _bizType60 = item.id;
                    item.isSelected = true;
                  } else {
                    item.isSelected = false;
                  }
                  dataList.add(item);
                }
              }
            } else {}
          } else {
            Toast.show(map["msg"]);
          }
        } else {
          Toast.show(map["msg"]);
        }
      } else {
        Toast.show(r.statusCode.toString());
      }
    }).catchError((e) {
      // page.closeProgress();
      Log.d("", e.toString());
      Toast.show(getErrorMessage(e));
    });
  }

  bool _hasHealthData() {
    if (_highPreValue == "-" &&
        _lowPreValue == "-" &&
        _oxygenValue == "-" &&
        _heartValue == "-" &&
        _temperatureValue == "-" &&
        _bloodSugarValue == "-") {
      return false;
    } else {
      return true;
    }
  }

  ///服务执行提交
  _bottomServiceSheetAlert() {
    showModalBottomSheet(
      backgroundColor: Colors.white,
      context: context,
      isScrollControlled: true,
      isDismissible: true,
      builder: (BuildContext context) {
        return StatefulBuilder(builder: (context, setDialogState) {
          return Container(
            width: double.infinity,
            height: ScreenUtil.getScreenH(context) * 2 / 3,
            padding: EdgeInsets.only(
                bottom: MediaQuery.of(context).viewInsets.bottom),
            child: Column(
              mainAxisAlignment: MainAxisAlignment.start,
              crossAxisAlignment: CrossAxisAlignment.center,
              children: <Widget>[
                Expanded(
                  child: ListView.separated(
                    itemBuilder: (_, int index) {
                      return Container(
                        padding:
                            EdgeInsets.only(right: 20, top: 10, bottom: 10),
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.start,
                          children: [
                            Checkbox(
                              value: dataList[index].isSelected,
                              onChanged: (value) {
                                setDialogState(() {
                                  dataList[index].isSelected = value;
                                });
                              },
                            ),
                            Expanded(
                              child: Text(
                                '${dataList[index].bizTypeName}',
                                style: TextStyles.textDark18,
                              ),
                            ),
                            Text(
                              '${dataList[index].planStartTime}',
                              style: TextStyles.textGray16,
                            )
                          ],
                        ),
                      );
                    },
                    separatorBuilder: (_, int index) => Gaps.line,
                    itemCount: dataList.length,
                  ),
                ),
                Gaps.vGap15,
                Container(
                  width: double.infinity,
                  height: 60,
                  padding: EdgeInsets.fromLTRB(20, 0, 20, 10),
                  decoration: BoxDecoration(
                    borderRadius: BorderRadius.circular(8),
                  ),
                  child: FlatsButton(
                    color: Colours.app_main,
                    onPressed: () {
                      Navigator.pop(context);
                      _sendNullServiceData();
                    },
                    child: Text(
                      '提交',
                      style: TextStyle(color: Colors.white),
                    ),
                  ),
                ),
              ],
            ),
          );
        });
      },
    );
  }
}
